<?php

class route_model extends CI_Model {

    public function __construct()
    {
       $this->load->database();
    }

    public function getRoutes()
    {
        $result =  $this->db->get_where('route')->result_array();
        return $result;
    }

    public function getRoute($route_id)
    {
        $result =  $this->db->get_where('route',['route_id'=>$route_id])->row_array();
        return $result;
    }

    public function createDriverRoute($data)
    {
        $data['route_type'] = 1;
        $data['status'] = 0;
        $data['main_route_id'] = 0;
        $this->insertRoute($data);
    }

    public function createPassengerRoute($data)
    {
        $data['route_type'] = 2;
        $data['status'] = 0;
        $data['main_route_id'] = 0;
        return $this->insertRoute($data);
    }

    public function applyDriver($data)
    {
        $route_id = $data['main_route_id'];
        $route = $this->getRoute($route_id);

        $data['departure'] = $route['departure'];
        $data['departure_city'] = $route['departure_city'];
        $data['departure_time'] = $route['departure_time'];
        $data['destination'] = $route['destination'];
        $data['destination_city'] = $route['destination_city'];
        $data['route_type'] = 2;
        $data['price'] = $route['price'];
        $data['total'] = round($data['seat_num'] * $route['price']);
        $data['status'] = 2;//待司机确认

        return $this->insertRoute($data);
    }

    public function invitePassenger($data)
    {
        $route_id = $data['route_id'];
        $passengerRoute = $this->getRoute($route_id);
        $driverRoute = $this->getRoute($data['main_route_id']);

        $route['main_route_id'] = $data['main_route_id'];
        $route['price'] = $driverRoute['price'];
        $route['total'] = round($passengerRoute['price'] * $passengerRoute['seat_num'],2);
        $route['status'] = 1;//待乘客确认
        $this->db->update('route',$route,['route_id'=>$route_id]);
    }
    public function insertRoute($data)
    {
        $data['date_added'] = date('Y-m-d H:i:s');
        $data['date_modified'] = date('Y-m-d H:i:s');
        $result = $this->db->insert('route',$data);

        if($result){
            return ['route_id'=>$this->db->insert_id()];
        }else{
            return false;
        }
    }



}